import { create } from "zustand";
import { nanoid } from "nanoid";

// 定义PresentationStore接口，包含所有需要的状态和方法
// 定义一个接口PresentationStore，用于存储幻灯片的相关信息
interface PresentationStore {
  // 更新幻灯片索引
  updatePowerPointIndex: (index: number) => void;
  // 创建幻灯片
  createPowerPoint: () => void;
  // 修改幻灯片
  modifyPowerPoint: (newSlideList: any[]) => void;
  // 删除幻灯片
  deletePowerPoint: (newSlideList: any[]) => void;
  // 修改幻灯片标题
  modifyPowerPointTitle: (newSlideTitle: any) => void;
  // 修改任意值
  modifyArbitraryValue: (newData: any) => void;
  // 幻灯片ID
  powerPointParId: string;
  // 幻灯片数组
  powerPointParArr: any[];
  // 幻灯片数组
  powerPointArr: any[];
  curpowerPointIndex: number;
  powerPointTitle: string;
  powerPointImage: string;
  PPtBgtype: string;
  PPtBgValue1: string;
  PPtBgValue2: string;
}

// 创建zustand store，并导出
export const useStore = create<PresentationStore>((set) => ({
  powerPointParId: "", // 幻灯片多组时的一个item的id
  powerPointParArr: [], // 幻灯片多组时的数组
  powerPointArr: [
    {
      sortId: 1, // 幻灯片排序id
      id: nanoid(), // 幻灯片id
      elements: [], // 幻灯片元素数组
    },
  ],
  curpowerPointIndex: 1, // 当前幻灯片索引
  powerPointTitle: "默认标题", // 幻灯片标题
  powerPointImage: "", // 幻灯片背景图片
  PPtBgtype: "color",
  PPtBgValue1: "",
  PPtBgValue2: "",
  // 更新当前幻灯片索引
  updatePowerPointIndex: (index) => {
    set(() => ({
      curpowerPointIndex: index,
    }));
  },
  // 创建新的幻灯片
  // 创建PPT
  createPowerPoint: () => {
    // 使用set函数更新state
    set((state) => {
      // 创建一个新的幻灯片，sortId为当前幻灯片数+1，id为nanoid生成的唯一标识，elements为空数组
      const newSlide = {
        sortId: state.powerPointArr.length + 1,
        id: nanoid(),
        elements: [],
      };
      // 将新幻灯片添加到state中的powerPointArr数组中
      const slideListBro = [...state.powerPointArr, newSlide];
      // 返回更新后的state
      return {
        powerPointArr: slideListBro,
      };
    });
  },
  // 修改幻灯片列表
  modifyPowerPoint: (newSlideList) => {
    set(() => ({
      powerPointArr: newSlideList,
    }));
  },
  // 删除幻灯片
  deletePowerPoint: (newSlideList) => {
    set(() => ({
      powerPointArr: newSlideList,
      curpowerPointIndex: 1,
    }));
  },
  // 修改幻灯片标题
  modifyPowerPointTitle: (newSlideTitle) => {
    set(() => ({
      powerPointTitle: newSlideTitle,
    }));
  },
  // 修改任意值
  modifyArbitraryValue: (newData) => {
    set(() => ({
      ...newData,
    }));
  },
}));
